<?php
function user_login_callback($type, $user) {
	global $db, $pe, $cache_setting;
	if (!is_array($user)) $user = $db->pe_select('user', array('user_id'=>$user));
	//$db->pe_update('user', array('user_id'=>$user['user_id']), array('user_ltime'=>time(), 'user_ldate'=>date('Y-m-d')));
	$db->pe_update('user', array('user_id'=>$user['user_id']), array('user_ltime'=>time()));
	$_SESSION['user_idtoken'] = md5($user['user_id'].$pe['host']);
	$_SESSION['user_id'] = $user['user_id'];
	$_SESSION['user_name'] = $user['user_name'];
	$_SESSION['user_ltime'] = $user['user_ltime'];
	$_SESSION['pe_token'] = pe_token_set($_SESSION['user_idtoken']);
	pe_set_session('user_id', $user['user_id']);
	if ($type == 'reg') {
		add_pointlog($user['user_id'], 'add', $cache_setting['point_reg'], '新用户注册奖励');
		userinfo_callback($user['user_id']);
		//记录推荐人
		$tguser_id = $_GET['u'] ? intval($_GET['u']) : intval($_COOKIE['tguser_id']);
		if ($tguser_id) {
			$tguser = $db->pe_select('user', array('user_id'=>$tguser_id), 'user_id, user_name');
			if ($tguser['user_id']) {
				$sql_set['tguser_id'] = $tguser['user_id'];
				$sql_set['tguser_name'] = $tguser['user_name'];	
				$db->pe_update('user', array('user_id'=>$user['user_id']), pe_dbhold($sql_set));
				add_pointlog($tguser['user_id'], 'add', $cache_setting['point_tg'], "邀请用户《{$user['user_name']}》注册奖励");	
				userinfo_callback($tguser['user_id']);
			}
		}	
	}
}

//用户信息回调
function userinfo_callback($user_id = 0) {
	global $db;
	$cache_userlevel = cache::get('userlevel');
	$cache_userlevel_arr = cache::get('userlevel_arr');
	if ($user_id == 'all') {
		$hand_id = implode("','", array_keys($cache_userlevel_arr['hand']));
		foreach ($cache_userlevel_arr['auto'] as $v) {
			//if ($v['userlevel_up'] == 'hand') continue;
			$db->pe_update('user', "and `user_money_cost` >= '{$v['userlevel_value']}' and `userlevel_id` not in('{$hand_id}')", array('userlevel_id'=>$v['userlevel_id']));
		}
	}
	else {
		$user = $db->pe_select('user', array('user_id'=>$user_id), 'userlevel_id, user_money_cost');
		if ($user['userlevel_id'] && $cache_userlevel[$user['userlevel_id']]['userlevel_up'] == 'hand') return true;
		foreach ($cache_userlevel_arr['auto'] as $v) {
			if ($user['user_money_cost'] >= $v['userlevel_value']) {
				$userlevel_id = $v['userlevel_id'];
			}
			else {
				break;
			}
		}
		if ($userlevel_id != $user['userlevel_id']) {
			$db->pe_update('user', array('user_id'=>$user_id), array('userlevel_id'=>$userlevel_id));
		}
		$user_tgnum = $db->pe_num('user', array('tguser_id'=>$user_id));
		$db->pe_update('user', array('user_id'=>$user_id), array('user_tgnum'=>$user_tgnum));
	}
}

//绑定微信openid
function user_bind_callback($user_id = 0, $user_wx_openid = '', $user_wx_unionid = '') {
	global $db;
	if (!$user_wx_openid) return false;
	$db->pe_update('user', array('user_id'=>$user_id), array('user_wx_openid'=>$user_wx_openid));
}

//记录交易明细
function add_moneylog($user_id, $type, $money, $text=null, $time='') {
	global $db;
	$money = pe_num($money, 'floor', 2);
	if ($money <= 0) return false;	
	if (!$user_id) return false;
	if (in_array($type, array('recharge', 'add', 'back', 'tg'))) {
		$sql_user = "`user_money` = `user_money` + '{$money}'";
		$sql_set['moneylog_in'] = $money;
	}
	else {
		$sql_user = "`user_money` = `user_money` - '{$money}'";
		$sql_set['moneylog_out'] = $money;
	}
	if ($db->pe_update('user', array('user_id'=>$user_id), $sql_user)) {
		$user = $db->pe_select('user', array('user_id'=>$user_id));
		$sql_set['moneylog_text'] = $text;
		$sql_set['moneylog_now'] = $user['user_money'];
		$sql_set['moneylog_atime'] = $time ? $time : time();
		$sql_set['moneylog_adate'] = date('Y-m-d', $sql_set['moneylog_atime']);
		$sql_set['moneylog_type'] = $type;
		$sql_set['user_id'] = $user['user_id'];
		$sql_set['user_name'] = $user['user_name'];
		$db->pe_insert('moneylog', pe_dbhold($sql_set, array('moneylog_text')));
		return true;
	}
	else {
		return false;
	}
}

//增加积分
function add_pointlog($user_id, $type, $point = 0, $text = null) {
	global $db;
	$point = intval($point);
	if (!$point) return false;	
	if (!$user_id) return false;
	if (in_array($type, array('add', 'back', 'tg'))) {
		$sqlset_user = " `user_point` = `user_point` + '{$point}'";
		$sql_set['pointlog_in'] = $point;
	}
	else {
		$sqlset_user = " `user_point` = `user_point` - '{$point}'";
		$sql_set['pointlog_out'] = $point;
	}
	if ($db->pe_update('user', array('user_id'=>$user_id), $sqlset_user)) {
		$user = $db->pe_select('user', array('user_id'=>$user_id));
		if (!$user['user_id']) return false;
		$sql_set['pointlog_text'] = $text;
		$sql_set['pointlog_now'] = $user['user_point'];
		$sql_set['pointlog_atime'] = time();
		$sql_set['pointlog_type'] = $type;
		$sql_set['user_id'] = $user['user_id'];
		$sql_set['user_name'] = $user['user_name'];
		$db->pe_insert('pointlog', pe_dbhold($sql_set, array('pointlog_text')));
		return true;
	}
	else {
		return false;
	}
}

//发放优惠券
function add_quanlog($user, $quan_id, $num = 1) {
	global $db;
	$info = $db->pe_select('quan', array('quan_id'=>$quan_id));
	if (!$info['quan_id']) return false;
	for ($i=1; $i<=$num; $i++) {
		$sql_set[$i]['quanlog_atime'] = time();
		$sql_set[$i]['quan_id'] = $info['quan_id'];
		$sql_set[$i]['quan_name'] = $info['quan_name'];
		$sql_set[$i]['quan_money'] = $info['quan_money'];
		$sql_set[$i]['quan_limit'] = $info['quan_limit'];
		if ($info['quan_datetype'] == 'relative') {
			$sql_set[$i]['quan_sdate'] = date('Y-m-d');
			$sql_set[$i]['quan_edate'] = date('Y-m-d', strtotime("+{$info['quan_day']} day"));	
		}
		else {
			$sql_set[$i]['quan_sdate'] = $info['quan_sdate'];
			$sql_set[$i]['quan_edate'] = $info['quan_edate'];
		}
		$sql_set[$i]['product_id'] = $info['product_id'];
		$sql_set[$i]['user_id'] = $user['user_id'];
		$sql_set[$i]['user_name'] = $user['user_name'];
	}
	if ($db->pe_insert('quanlog', pe_dbhold($sql_set))) {
		$db->pe_update('quan', array('quan_id'=>$info['quan_id']), array('quan_num_get'=>$info['quan_num_get'] + $num));
		return true;
	}
	else {
		return false;
	}
}

//增加购买记录
function add_buylog($user, $product_guid, $num, $atime = 0) {
	global $db;
	$num = intval($num);
	if (!$num) return false;
	$prodata = $db->pe_select('prodata', array('product_guid'=>$product_guid));
	$product = $db->pe_select('product', array('product_id'=>$prodata['product_id']));
	if (!$product['product_id']) return false;
	$sql_set['buylog_num'] = $num;
	$sql_set['buylog_atime'] = $atime ? $atime : time();
	$sql_set['buylog_adate'] = pe_date($sql_set['buylog_atime'], 'Y-m-d');
	$sql_set['product_id'] = $product['product_id'];
	$sql_set['product_name'] = $product['product_name'];
	$sql_set['product_logo'] = $product['product_logo'];
	$sql_set['product_rule'] = $prodata['product_rulename'];
	$sql_set['product_money'] = $prodata['product_money'];
	$sql_set['user_id'] = $user['user_id'];
	$sql_set['user_name'] = $user['user_name'];
	$sql_set['user_logo'] = $user['user_logo'];
	if ($db->pe_insert('buylog', pe_dbhold($sql_set, array('product_rule')))) {
		return true;
	}
	else {
		return false;
	}
}

//添加抽奖机会
function add_jianglog($user, $from = '') {
	global $db;
	$user = is_array($user) ? $user : $db->pe_select('user', array('user_id'=>intval($user)));
	$sql_set['choujianglog_atime'] = time();
	$sql_set['choujianglog_adate'] = date('Y-m-d');
	$sql_set['choujianglog_edate'] = '2099-01-01';
	$sql_set['choujianglog_state'] = 'wuse';
	$sql_set['choujianglog_from'] = $from;
	$sql_set['user_id'] = $user['user_id'];
	$sql_set['user_name'] = $user['user_name'];
	$sql_set['user_logo'] = $user['user_logo'];
	if ($db->pe_insert('choujianglog', pe_dbhold($sql_set))) {
		return true;
	}
	else {
		return false;
	}
}

//获取用户金额
function user_money($user_id, $type = '') {
	global $db;
	$user = $db->pe_select('user', array('user_id'=>$user_id), "`user_money`");
	//申请提现中金额
	$cashout = $db->pe_select('cashout', array('user_id'=>$user_id, 'cashout_state'=>0), "sum(`cashout_money`) as `money`");
	//冻结金额
	$user_lock = round($cashout['money'], 1);	
	$user_real = round($user['user_money'], 1);
	//浮点数精度问题，相减round后等于-0(2015-08-19修正)
	if ($user_real == '-0') $user_real = 0;
	$money_arr = array('all'=>$user['user_money'], 'real'=>$user_real, 'lock'=>$user_lock);
	if ($type) {
		return $money_arr[$type];
	}
	else {
		return $money_arr;
	}
}

//获取用户积分
function user_point($user_id, $type = '') {
	global $db, $cache_setting;
	$user = $db->pe_select('user', array('user_id'=>$user_id), "`user_point`");
	//冻结积分
	$order = $db->pe_select('order', array('user_id'=>$user_id, 'order_state'=>array('notpay', 'paid', 'send')), "sum(`order_point_use`) as `point`");
	//冻结金额
	$user_lock = $order['point'];	
	$user_real = round($user['user_point'] - $user_lock, 1);
	$user_money = $cache_setting['point_money'] ? round($user_real/$cache_setting['point_money'], 1) : 0;
	$point_arr = array('all'=>$user['user_point'], 'real'=>$user_real, 'lock'=>$user_lock, 'money'=>$user_money);
	if ($type) {
		return $point_arr[$type];
	}
	else {
		return $point_arr;
	}
}

//获取用户等级
function get_userlevel($user, $key = null, $real = false){
	global $db;
	$cache_userlevel = cache::get('userlevel');
	$userlevel_id = $user['userlevel_id'];
	if (!is_array($cache_userlevel[$userlevel_id]) or $cache_userlevel[$userlevel_id]['userlevel_up'] == 'auto' or $real) {
		foreach ($cache_userlevel as $v) {
			if ($v['userlevel_up'] == 'hand') continue;
			if ($user['user_money_cost'] >= $v['userlevel_value']) {
				$userlevel_id = $v['userlevel_id'];
			}
			else {
				break;
			}
		}	
	}
	return $key ? $cache_userlevel[$userlevel_id][$key] : $cache_userlevel[$userlevel_id];
}

//上级推荐人
function tguser_list($user_id = 0, $alllevel = 1, $nowlevel = 1, $tguser_list = array()) {
	global $db;
	if (!$user_id) return $tguser_list;
	if ($nowlevel == 1) {
		$user = $db->pe_select('user', array('user_id'=>$user_id), 'tguser_id');
		$user_id = $user['tguser_id'];
	}
	if ($nowlevel <= $alllevel) {
		$tguser_list[$nowlevel] = $db->pe_select('user', array('user_id'=>$user_id));
		return tguser_list($tguser_list[$nowlevel]['tguser_id'], $alllevel, $nowlevel+1, $tguser_list);
	}
	else {
		return $tguser_list;
	}
}

//下级用户列表
function xjuser_list($user_id = 0, $alllevel = 1000, $nowlevel = 1) {
	global $db, $xjuser_list;
	if (!$user_id) return true;
	if ($nowlevel > $alllevel) return true;
	$xjuser_list[$nowlevel] = $db->pe_selectall('user', array('tguser_id'=>$user_id));
return ;
	foreach ($xjuser_list[$nowlevel] as $k=>$v) {
		xjuser_list($v['user_id'], $alllevel, $nowlevel + 1);
	}
}

//获取可用优惠券
function user_quanlist($cart) {
	global $db, $user;
	user_quancheck();
	$info_list = $db->index('quanlog_id')->pe_selectall('quanlog', array('user_id'=>$user['user_id'], 'quanlog_state'=>0, 'order by'=>'quan_money desc, quanlog_atime desc'));
	$quan_list[0] = array('quanlog_id'=>0, 'quan_id'=>0, 'quan_name'=>'不使用优惠券', 'quan_show'=>'不使用优惠券', 'quan_money'=>0);
	foreach ($info_list as $k=>$v) {
		if ($v['quan_sdate'] > date('Y-m-d')) continue;
		$v['quan_show'] = "省{$v['quan_money']}元：{$v['quan_name']}";
		if ($v['product_id']) {
			$product_money = 0;
			foreach ($cart['list'] as $vv) {
				if (in_array($vv['product_id'], explode(',', $v['product_id']))) {
					$product_money += $vv['product_money'] * $vv['product_num'];
				}
			}
			if ($product_money >= $v['quan_limit']) $quan_list[$k] = $v;
		}
		else {
			if ($cart['order_product_money'] >= $v['quan_limit']) $quan_list[$k] = $v;
		}
	}
	return $quan_list;
}

//检测优惠券是否过期
function user_quancheck() {
	global $db;
	$nowdate = date('Y-m-d');
	$db->pe_update('quan', " and `quan_datetype` = 'absolute' and `quan_state` = 1 and `quan_edate` < '{$nowdate}'", array('quan_state'=>0));
	$db->pe_update('quanlog', " and `quanlog_state` = 0 and `quan_edate` < '{$nowdate}'", array('quanlog_state'=>2));
	$db->pe_update('quanlog', " and `quanlog_state` = 2 and `quan_edate` >= '{$nowdate}'", array('quanlog_state'=>0));
}

//更新优惠券状态
function user_quanupdate($quanlog_id, $state) {
	global $db;
	if (!$quanlog_id) return false;
	$sql_set['quanlog_utime'] = $state == 1 ? time() : 0;
	$sql_set['quanlog_state'] = intval($state);	
	$db->pe_update('quanlog', array('quanlog_id'=>intval($quanlog_id)), $sql_set);
	//统计领取数和使用数
	$info = $db->pe_select('quanlog', array('quanlog_id'=>intval($quanlog_id)), 'quan_id');	
	$quan_num_get = $db->pe_num('quanlog', "and `quan_id` = '{$info['quan_id']}' and `user_id` > 0");
	$quan_num_use = $db->pe_num('quanlog', "and `quan_id` = '{$info['quan_id']}' and `user_id` > 0 and `quanlog_state` = 1");
	$db->pe_update('quan', array('quan_id'=>$info['quan_id']), array('quan_num_get'=>$quan_num_get, 'quan_num_use'=>$quan_num_use));
	user_quancheck();
}

//获取用户二维码
function user_qrcode($url) {
	global $pe, $db;
	$info = $db->pe_select('user', array('user_id'=>$_SESSION['user_id']), 'user_logo');
	//$user_logo = $info['user_logo'] ? str_ireplace($pe['host'], $pe['host_path'], pe_thumb($info['user_logo'], '_120', '_120', 'avatar')) : '';
	$user_logo = $info['user_logo'] ? pe_thumb($info['user_logo'], '_120', '_120', 'avatar') : '';
	$user_qrcode = "{$pe['path']}data/cache/thumb/".date('Y-m')."/".md5($url).".png";
	if (!is_file($user_qrcode)) {
		if (!is_dir("{$pe['path']}data/cache/thumb/".date('Y-m'))) {
			mkdir("{$pe['path']}data/cache/thumb/".date('Y-m'), 0777, true);		
		}
		pe_lead('include/class/phpqrcode.class.php');
		QRcode::png($url, $user_qrcode);
	}
	if ($user_logo) {
		$qrcode = imagecreatefromstring(file_get_contents($user_qrcode));
		$logo = imagecreatefromstring(file_get_contents($user_logo));
		$QR_width = imagesx($qrcode);//二维码图片宽度
		$QR_height = imagesy($qrcode);//二维码图片高度
		$logo_width = imagesx($logo);//logo图片宽度
		$logo_height = imagesy($logo);//logo图片高度
		$logo_qr_width = $QR_width / 5;
		$scale = $logo_width / $logo_qr_width;
		$logo_qr_height = $logo_height / $scale;
		$from_width = ($QR_width - $logo_qr_width) / 2;
		//重新组合图片并调整大小
		imagecopyresampled($qrcode, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
		//输出图片
		imagepng($qrcode, $user_qrcode);
	}
	return "{$pe['host']}data/cache/thumb/".date('Y-m')."/".md5($url).".png";	
}

//显示收款账号
function userbank_num($val) {
	if (preg_match("/^\d{16,20}$/", $val)) {
		$val = substr($val, 0, 4).'**'.substr($val, -4);
	}
	elseif (stripos($val, '@') !== false) {
		$val = substr($val, 0, 3).'**'.stristr($val, '@');
	}
	elseif (strlen($val) > 8) {
		$val = substr($val, 0, 3).'**'.stristr($val, '@');
	}
	return $val;
}

//根据手机号生成用户名
function user_jsname($name, $arg = '') {
	global $db;
	$user_name = preg_replace_callback('/./u', function (array $match) {
			return strlen($match[0]) >= 4 ? '' : $match[0];
		}, $name);
	//$name = preg_replace('/[\xf0-\xf7].{3}/', '', $name);
	$user_name = trim($user_name);
	//$name = trim(preg_replace("/[\x{1F600}-\x{1F64F}\x{1F300}-\x{1F5FF}\x{1F680}-\x{1F6FF}\x{2600}-\x{26FF}\x{2700}-\x{27BF}]/u","",$name));
	if ($user_name && !$db->pe_select('user', array('user_name'=>pe_dbhold($user_name)))) return $user_name;
	//使用指定字符重命名
	if (!$user_name) $user_name = 'pe';
	$arg = substr($arg, -8);
	if (!$arg) $arg = mt_rand(100,999);
	$user_name = "{$user_name}_{$arg}";
	$info = $db->pe_select('user', array('user_name'=>pe_dbhold($user_name)), 'user_id');
	if ($info['user_id']) {
		return user_jsname($name);
	}
	else {
		return $user_name;
	}
}

//用户登录token
function user_token($info) {
	global $db, $ini;
	if (!is_array($info)) $info = $db->pe_select('user', array('user_id'=>$info));
	if (!$info['user_token'] or time() - $info['user_ltime'] >= $ini['login_timeout']) {
		$token = md5($info['user_id'].microtime(true).pe_ip());
		$db->pe_update('user', array('user_id'=>$info['user_id']), array('user_token'=>$token, 'user_ltime'=>time()));
		return $token;
	}
	else {
		return $info['user_token'];
	}
}

//游客信息（针对未登录用户）
function user_guest() {
	global $pe, $cache_setting;
	$user = array();
	if (in_array($pe['client'], array('','h5')) && $cache_setting['web_guestbuy']) {
		$user['user_id'] = pe_user_id();
		$user['user_name'] = '游客_'.substr($user['user_id'], '-6');	
	}
	return $user;
}

//添加足迹
function add_footprint($info) {
	global $db, $user;
	if (!$user['user_id']) return;
	$sql_set['footprint_utime'] = time();
	$sql_set['product_id'] = $info['product_id'];
	$sql_set['product_name'] = $info['product_name'];
	$sql_set['product_logo'] = $info['product_logo'];
	$footprint = $db->pe_select('footprint', array('product_id'=>$info['product_id'], 'user_id'=>$user['user_id']));
	if ($footprint['footprint_id']) {
		$db->pe_update('footprint', array('footprint_id'=>$footprint['footprint_id']), pe_dbhold($sql_set));
	}
	else {
		$sql_set['footprint_atime'] = time();
		$sql_set['user_id'] = $user['user_id'];
		$sql_set['user_name'] = $user['user_name'];
		$db->pe_insert('footprint', pe_dbhold($sql_set));	
	}
}
